/**
 * QIBAO Service Inc
 * All Rights Reserved @2019
 */
package com.qibao.toolkit.util;


import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.MDC;

import java.util.Map;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * <p>logMDC的线程。</p>
 * @author zhanghui
 */
public class MdcRunnable implements Runnable {

    /**
     * 日志输出对象
     */
    private static final Logger LOGGER = getLogger(MdcRunnable.class);


    private Map<String, String> mdcContext;

    private Runnable runnable;

    public MdcRunnable(Map<String, String> mdcContext, Runnable runnable) {

        this.mdcContext = mdcContext == null ? Maps.newHashMap() : mdcContext;
        this.runnable = runnable;

    }

    @Override
    public void run() {

        MDC.setContextMap(mdcContext);

        try {

            runnable.run();

        } catch (Throwable e) {

            LOGGER.error(String.format("%s thread throw exception", Thread.currentThread().getName()), e);
            throw e;

        } finally {

            MDC.clear();

        }

    }

}